import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;


public class FormRequest extends Request<JSONObject> {
	private Map<String, String> mParams;
	private Listener<JSONObject> mListener;
	private static Cookies cookies;
	public FormRequest(int method, String url, Map<String, String> params, Listener<JSONObject> listener, ErrorListener errorListener) {
		super(method, url, errorListener);
		mParams = params;
		mListener = listener;
		setShouldCache(false);
		cookies = new Cookies();
	}
	

	@Override
	protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
		String string = null;
		try {
			string = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
			cookies.addCookies(response.headers);
			System.out.println(cookies.getStrCookies());
			//System.out.println(string);
			return Response.success(new JSONObject(), HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return Response.error(new ParseError(e));
		}
		
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		// TODO Auto-generated method stub
		return mParams;
	}
	
	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		if(cookies.getCookies().size() != 0){
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("Cookie", cookies.getStrCookies());
			return hashMap;
		}
		return super.getHeaders();
	}
	
	@Override
	protected void deliverResponse(JSONObject response) {
		mListener.onResponse(response);
	}

	@Override
	public String getUrl() {
		String url = super.getUrl();
		if(getMethod() == Method.GET && mParams != null && mParams.size() != 0){
			url = rewriteUrl(url);
		}
		System.out.println(url);
		return url;
	}
	
	private String rewriteUrl(String url){
		StringBuffer sb = new StringBuffer(url);
		if(sb.indexOf("?") != -1){
			sb.append("&");
		}else{
			sb.append("?");
		}
		for(Map.Entry<String, String> param: mParams.entrySet()){
			sb.append(param.getKey());
			sb.append("=");
			sb.append(param.getValue());
			sb.append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}
}
